<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">班级管理-详情</div>
        </div>
        <div class="header-right">
          <img src="../../assets/images/back.png" class="addmsg1" @click="getback">
          <img src="../../assets/images/加号.png" class="addmsg" @click="handleAdd" v-if="status != '2' && user.roleId != '5'"/>
        </div>
      </div>
    </div>

    <div class="class-content">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="studentName" label="姓名" align="center" />
        <el-table-column prop="sex" label="性别" align="center" />
        <el-table-column prop="tel" label="电话" align="center" />
        <el-table-column prop="address" label="家庭住址" align="center">
          <template #default="scoped">
            {{scoped.row.address? scoped.row.address : '---'}}
          </template>
        </el-table-column>
        <el-table-column prop="emContact" label="紧急联系人" align="center">
          <template #default="scoped">
            {{scoped.row.emContact? scoped.row.emContact : '---'}}
          </template>
        </el-table-column>
        <el-table-column prop="emTel" label="紧急联系人电话" align="center" >
          <template #default="scoped">
            {{scoped.row.emTel? scoped.row.emTel : '---'}}  
          </template>
        </el-table-column>
        <el-table-column prop="saleName" label="销售顾问" align="center" >
          <template #default="scoped">
            {{scoped.row.saleName ? scoped.row.saleName : '管理员'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="user.roleId != '5'&& status != '2'" align="center">
          <template #default="scoped" >
            <el-button link type="success" @click="handleEdit(scoped.row)">修改</el-button>
            <el-button link type="danger" @click="handleDel(scoped.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentPageChange"
        />
        <div> 
            每页
            <el-input-number
              v-model="pageSize"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange"
            />条
        </div>

      </div>
    </div>
    <!-- 修改学生数据 -->
    <el-dialog v-model="dialogVisible" title="修改学生信息" :show-close="false">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="140px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="姓名" prop="studentName">
            <el-input v-model="formData.studentName" />
          </el-form-item>
          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="formData.address" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData.sex" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="紧急联系人" prop="emContact">
            <el-input v-model="formData.emContact" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="电话" prop="tel">
            <el-input v-model="formData.tel" />
          </el-form-item>
          <el-form-item label="紧急联系人电话" prop="emTel">
            <el-input v-model="formData.emTel" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-dialog>
    <!-- 添加学生数据 -->
      <el-dialog v-model="dialogVisible1" title="添加学生" :show-close="false">
      <div class="form-container"> 
        <el-form
          :model="formData1"
          label-width="140px"
          hide-required-asterisk
        >
          <el-row>
            <el-form-item label="班级:" prop="className">
              <el-select v-model="formData1.classId" placeholder="请选择班级" @change="ClassChange">
                <el-option
                  v-for="item in classList"
                  :key="item.classId"
                  :label="item.className"
                  :value="item.classId"
                />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <el-form-item label="选择学生:">
          <!-- 新增 div 容器 -->
          <div class="student-scroll-container">
            <el-checkbox-group v-model="studentId" class="checkbox-group">
                  <el-checkbox v-for="student in studentList"  :key="student.studentId" :value="student.studentId" style="margin-right: 10px;">{{ student.studentName }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </div>
      <template #footer>
        <el-button @click="dialogVisible1 = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm1" class="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router' // 导入 useRoute 钩子函数
import { ElMessage, ElMessageBox } from 'element-plus' // 导入 ElMessage 组件
import {
  getClassDetails,
  updateClassDetails,
  deleteStudent,
  getClassList,
  getStudentList,
  addStudent,
  getClassById,
} from '../api/ClassDetails' // 导入接口

const route = useRoute() // 获取当前路由对象
const classId = Number(route.query.classId) // 获取 classId 参数
const status = route.query.status // 获取 status 参数
//表格数据
const tableData = ref([])
//分页数据
const currentPage = ref(1) // 当前页码
const pageSize = ref(7) // 每页显示条数
const total = ref(0) // 总条数
//班级下拉框
const classList = ref([]) // 班级列表
//班级下面学生列表
const studentList = ref([]) // 学生列表
//添加的学生id
const studentId = ref([]) // 学生id

//本地存储
const user = JSON.parse(localStorage.getItem('user')) // 获取用户信息


//班级下拉框
function fetchClassList() {
  let data = {}
  getClassList('classList2', data).then((res) => {
    if (res.code == 200) {
      classList.value = res.dataset
    }
  })
}

//根据班级ID获取学生列表
function fetchStudentList(classId) {
  let data = { classId: classId }
  getStudentList('studentClassById', data).then((res) => {
    if (res.code == 200) {
      studentList.value = res.dataset
    }
  })
}

const className1 = ref('');
//根据班级ID获取班级信息
function fetchClassById(classId) {
  let data = { classId: classId }  
  getClassById('ClassById', data).then((res) => {
    if (res.code == 200) {
       className1.value = res.dataset.className;
    }
  })
}

//班级详情接口
function fetchData() {
  let data = {
    classId: classId,
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  getClassDetails('studentInfoList', data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.studentInfoList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

// 数据加载
onMounted(() => {
  document.querySelector('.classone').classList.add('classoneafter')
  fetchData()
  fetchClassList()
  fetchClassById(classId)
})

// 处理当前页变化
const handleCurrentPageChange = (value) => {
  currentPage.value = value
  fetchData(currentPage.value, pageSize.value)
}

//模态框
const dialogVisible = ref(false) // 控制对话框的显示和隐藏
const formData = ref({
  studentName: '',
  sex: '',
  tel: '',
  address: '',
  emContact: '',
  emTel: '',
})
const rules = {
  // 表单验证规则
  studentName: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  tel: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  emTel: [
    { 
      validator: (rule, value, callback) => {
        if (value && !/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      },
      trigger:  'blur'
    }
  ],
  // address: [
  //   { required: true, message: '请输入家庭住址', trigger: 'blur' },
  //   { min: 2, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' },
  // ],
  // emContact: [
  //   { required: true, message: '请输入紧急联系人', trigger: 'blur' },
  //   { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  // ],
  // emTel: [
  //   { required: true, message: '请输入紧急联系人电话', trigger: 'blur' },
  //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  // ],
}
const formRef = ref(null) // 表单引用

// 编辑学生信息
const handleEdit = (row) => {
  dialogVisible.value = true // 显示对话框
  formData.value = { ...row } // 将当前行的数据复制到表单数据中
}

//修改学生信息接口
function updateClassDetail() {
  let data = {
    studentName: formData.value.studentName,
    sex: formData.value.sex,
    tel: formData.value.tel,
    address: formData.value.address,
    emContact: formData.value.emContact,
    emTel: formData.value.emTel,
    studentId: formData.value.studentId,
  }
  updateClassDetails('updateStudentInfo', data).then((res) => {
    if (res.code == 200) {
      ElMessage.success('修改成功')

      fetchData()
    }
  })
}

// 确认修改
const handleConfirm = () => {
  //确认修改逻辑
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('确定要修改该学生信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        updateClassDetail()
        dialogVisible.value = false // 隐藏对话框
      })
    } else {
      return false
    }
  })
}

//删除接口
function deleteStudentInfo(studentId) {
  let data = {
    studentId,
  }
  deleteStudent('deleteStudentInfo', data).then((res) => {
    if (res.code == 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  })
}

// 删除学生信息
const handleDel = (row) => {
  ElMessageBox.confirm('确定要删除该学生信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteStudentInfo(row.studentId)
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

//添加的表单数据
const formData1 = ref({
  studentId: '',
  classId: '',
  className: className1.value,
})
const rules1 = {
  // 表单验证规则
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
}
// const formRef1 = ref(null) // 表单引用
//添加学生信息
const dialogVisible1 = ref(false) // 控制对话框的显示和隐藏

//点击添加
const handleAdd = () => {
  // 清空表单数据
  formData1.value = {
    studentId: '',
    classId: '',
    className: className1.value,
  }
  studentList.value = [];
  dialogVisible1.value = true // 显示对话框
}

//班级下拉框切换
function ClassChange() {
  formData1.value.className = classList.value.find(
    (item) => item.classId === formData1.value.classId
  ).className
  // 调用接口获取学生列表
  fetchStudentList(formData1.value.classId)
}

// 添加学生信息接口
function addStudentInfo() {

  let data = {
    classId: classId,
    className: className1.value,
  } 
  for (let i = 0; i < studentId.value.length; i++) {
    data.studentId = studentId.value[i]
    addStudent('addStudentsByCourse', data).then((res) => {
      if (res.code == 200) {
         fetchData();
      }
    }) 
  }
}

//点击确认
function handleConfirm1() {
  //确认修改逻辑
  if(studentId.value.length == 0){
    ElMessage.error('请选择学生')
    return false
  }else{
    ElMessageBox.confirm('确定要添加该学生信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning', 
    }).then(() => {
      addStudentInfo()
      ElMessage.success('添加成功')
      dialogVisible1.value = false // 隐藏对话框
      studentId.value=[];
    }).catch(() => {
      ElMessage.info('已取消添加')
    })
  }
}

function getback() {
  window.history.go(-1)
}

function handleChange() {
  currentPage.value = 1; // 重置当前页码为第一页
  fetchData(); // 重新获取数据
}


</script>

<style scoped>

.class {
  width: 90%;
  height: 10%;
  margin-bottom: 20px;
  margin-top: 20px;
}

.line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
  margin-left: 40px;
}
.title {
  padding-left: 10px;
  font-size: 20px;
  margin-right: 20px;
}
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}
.addmsg1{
  width: 25px;
  height: 25px;
  margin-right: 20px;
  cursor:pointer;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.del) {
  margin-left: 55px;
}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}
/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-dialog__body){
  display: flex;
  justify-content: center;
}
:deep(.el-select) {
  width: 200px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}

.form-container {
  display: flex;
  gap: 20px; /* 两个区域之间的间距 */
}
 /* 让两个区域平均分配宽度 */

.student-scroll-container {
  max-height: 100px; 
  overflow-y: auto; 
  min-width: 260px;
}
.checkbox-group {
  display: grid; /* 使用网格布局 */
  grid-template-columns: repeat(3, 1fr); /* 每行显示四个列 */
}
</style>